package com.ljw.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ljw.common.to.SkuHasStockVo;
import com.ljw.common.to.mq.OrderTo;
import com.ljw.common.utils.R;
import com.ljw.gulimall.order.constant.OrderConstant;
import com.ljw.gulimall.order.entity.OrderItemEntity;
import com.ljw.gulimall.order.entity.PaymentInfoEntity;
import com.ljw.gulimall.order.enume.OrderStatusEnum;
import com.ljw.gulimall.order.exception.NoStockException;
import com.ljw.gulimall.order.feign.CartFeignService;
import com.ljw.gulimall.order.feign.MemberFeignService;
import com.ljw.gulimall.order.feign.ProductFeignService;
import com.ljw.gulimall.order.feign.WmsFeignService;
import com.ljw.gulimall.order.interceptor.LoginUserInterceptor;
import com.ljw.gulimall.order.service.OrderItemService;
import com.ljw.gulimall.order.service.PaymentInfoService;
import com.ljw.gulimall.order.to.OrderCreateTo;
import com.ljw.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljw.common.utils.PageUtils;
import com.ljw.common.utils.Query;

import com.ljw.gulimall.order.dao.OrderDao;
import com.ljw.gulimall.order.entity.OrderEntity;
import com.ljw.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVo = new ThreadLocal<>();

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 生成订单
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        Long memberId = memberVo.getId();
        //异步调用会导致老线程的request丢失，此步骤为获取老线程的request
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        //1、远程查询所有的收货地址列表
        //用户的id
        CompletableFuture<Void> addressCompletableFuture = CompletableFuture.runAsync(() -> {
            //设置新线程的request
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberId);
            confirmVo.setAddress(address);
        }, executor);

        //2、远程查询购物车所有选中的购物项
        CompletableFuture<Void> itemCompletableFuture = CompletableFuture.runAsync(() -> {
            //设置新线程的request
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wmsFeignService.getSkuHasStock(skuIds);
            List<SkuHasStockVo> skuHasStockVo = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
            });
            if (skuHasStockVo != null){
                Map<Long, Boolean> collect = skuHasStockVo.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(collect);
            }

        }, executor);
        //3、查询用户的积分
        Integer integration = memberVo.getIntegration();
        confirmVo.setIntegration(integration);

        try {
            Integer count = new Integer(0);
            CompletableFuture.allOf(addressCompletableFuture, itemCompletableFuture).get();
            //4、设置订单总价和订单商品总数量
            BigDecimal totalPrice = new BigDecimal(0);
            if (confirmVo.getItems() != null && confirmVo.getItems().size() > 0){
                for (OrderItemVo item : confirmVo.getItems()) {
                    totalPrice = item.getTotalPrice().add(totalPrice);
                    count = count + item.getCount();
                }
            }
            confirmVo.setTotal(totalPrice);
            confirmVo.setCount(count);
            confirmVo.setPayPrice(confirmVo.getTotal());

        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
        //TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId(), token, 30L, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        return confirmVo;
    }

    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        this.orderSubmitVo.set(orderSubmitVo);
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        //去创建订单，验令牌，验价格，锁库存......
        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //脚本返回值只会是0和1，0代表失败，1代表成功
        String scrip = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        //原子验证令牌和删除令牌
        //new DefaultRedisScript<Long>(scrip, Long.class)中的Long表示execute执行后的返回值，scrip表示lua脚本
        //Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId())表示传入的key
        //orderToken表示比较的token
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(scrip, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), orderToken);
        if (result == 0L){
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //1、令牌验证成功
            //接下来去创建订单，验令牌，验价格，所库存......
            OrderCreateTo order = this.createOrder();
            //生成订单的应付价格于前端传过来的做对比
            //2、金额对比
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //3、保存订单
                this.saveOrder(order);
                //4、库存锁定。只要有异常回滚订单数据
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                //TODO 远程锁库存
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0){
                    //锁定订单成功
                    responseVo.setOrder(order.getOrder());
                    //TODO 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                }else {
                    //锁定订单失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
//        String redisOrderToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        if (orderToken != null && orderToken.equals(redisOrderToken)){
//            //令牌验证通过
//
//        }else {
//            return null;
//        }
    }

    /**
     * 根据订单号查询订单
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn);
        OrderEntity orderEntity = baseMapper.selectOne(wrapper);
        return orderEntity;
    }

    /**
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询这个订单的最新状态
        Long id = entity.getId();
        OrderEntity orderEntity = baseMapper.selectById(id);
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(id);
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    /**
     * 获取订单的支付信息
     * @return
     * @param orderSn
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity orderEntity = this.getOrderStatus(orderSn);
        PayVo payVo = new PayVo();
        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemEntities.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 查询用户的订单购物项信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> collect = page.getRecords().stream().map(orderEntity -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, orderEntity.getOrderSn()));
            orderEntity.setOrderItemEntityList(orderItemEntities);
            return orderEntity;
        }).collect(Collectors.toList());

        page.setRecords(collect);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水信息
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);
        //2、修改订单状态
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String orderSn = vo.getOut_trade_no();
            baseMapper.updateOrderPayedStatus(orderSn, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }


    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }


    private OrderCreateTo createOrder(){
        OrderCreateTo orderTo = new OrderCreateTo();
        //1、生成订单号,利用Mybatis-plus提供的根据时间生成唯一Id的方法做为商品的订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = this.buildOrder(orderSn);
        //2、获得所有的订单项
        List<OrderItemEntity> orderItemEntities = this.buildOrderItems(orderSn);
        //3、计算价格相关
        computePrice(orderEntity, orderItemEntities);

        orderTo.setOrder(orderEntity);
        orderTo.setOrderItems(orderItemEntities);

        return orderTo;
    }

    /**
     * 计算订单总价
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal gift = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            total = total.add(orderItemEntity.getRealAmount());
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        //1、订单总价格
        orderEntity.setTotalAmount(total);
        //应付总额 = 总订单额+运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        //设置积分信息
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建订单项数据集合
     * @param
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //2、获取到所有的订单项
        List<OrderItemVo> currentUserItems = cartFeignService.getCurrentUserItems();
        if (currentUserItems != null && currentUserItems.size() > 0){
            List<OrderItemEntity> itemEntities = currentUserItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = this.buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //3、商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【不做】
        //5、积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //6、订单项的优惠价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际价格
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal realPrice = originPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;

    }

    private OrderEntity buildOrder(String orderSn){
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberVo.getId());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = this.orderSubmitVo.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费金额
        orderEntity.setFreightAmount(fareResp.getFare());
        //设置收货人的城市
        orderEntity.setReceiverCity(fareResp.getAddressVo().getCity());
        //设置收货人的详情地址
        orderEntity.setReceiverDetailAddress(fareResp.getAddressVo().getDetailAddress());
        //设置收货人的名字
        orderEntity.setReceiverName(fareResp.getAddressVo().getName());
        //设置收货人的手机号
        orderEntity.setReceiverPhone(fareResp.getAddressVo().getPhone());
        //设置收货人的邮编
        orderEntity.setReceiverPostCode(fareResp.getAddressVo().getPostCode());
        //省
        orderEntity.setReceiverProvince(fareResp.getAddressVo().getProvince());
        //区域
        orderEntity.setReceiverRegion(fareResp.getAddressVo().getRegion());

        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        //
        return orderEntity;
    }

}